package com.wang.thread;

import com.wang.server.Server;
import com.wang.util.LeakyBucket;

import java.net.Socket;
import java.util.LinkedList;

/**
 * 漏桶计计时器
 * Created by wang on 2017/5/3.
 */
public class LeakyBucketTimer implements Runnable {
    private Socket socket;
    private final LinkedList<Socket> list;
    public LeakyBucketTimer(LinkedList<Socket> list) {
        this.list = list;
    }

    @Override
    public void run() {
        while (true) {
            //如果桶中没有请求，等待
            synchronized (list) {
                if (list.size() == 0) {
                    try {
                        list.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
            //睡一秒取出线程
            try {
                Thread.sleep(800);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (list.size()!=0)
            socket=LeakyBucket.getSocket();
            if (socket != null) {
                Server.doService(socket);
                System.out.println("桶内还有"+ list.size()+"个请求");
            }
        }
    }
}
